package com.cpp.server.controller;

import com.cpp.common.constant.ModuleConstant;
import com.cpp.pojo.pojo.User;
import com.cpp.pojo.vo.others.MessageVO;
import com.cpp.server.aspect.annotation.MyLog;
import com.cpp.server.context.UserHolder;
import com.cpp.server.repository.ChatHistoryRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.util.List;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;

@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/chat")
public class ChatController {
    //自己定义的map集合，存放chatId
    private final ChatHistoryRepository chatHistoryRepository;
    private final ChatClient studnetChatClient;
    private final ChatMemory chatMemory;

    @MyLog(module = ModuleConstant.CHAT)
    @GetMapping("/history")
    public List<MessageVO> getChatHistory() {
        User currentUser = UserHolder.getCurrentUser();
        List<Message> messages = chatMemory.get(String.valueOf(currentUser.getId()), Integer.MAX_VALUE);
        if (messages == null) {
            return List.of();
        }
        return messages.stream().map(MessageVO::new).toList();
    }

    @MyLog(module = ModuleConstant.CHAT)
    @RequestMapping(value = "/chat", produces = "text/html;charset=utf-8")
    public Flux<String> chat(
            @RequestParam("prompt") String prompt
    ) {
        String userId = String.valueOf(UserHolder.getCurrentUser().getId());
//        chatHistoryRepository.save("chat", userId);
        return studnetChatClient.prompt()
                .user(prompt)
                .advisors(a -> a.param(CHAT_MEMORY_CONVERSATION_ID_KEY, userId))
                .stream()
                .content();

    }

}
